package com.echo.fm.content.news;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.List;
import java.util.Locale;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.echo.fm.admin.auto.model.Admin;
import com.echo.fm.content.news.model.News;
import com.echo.fm.content.news.model.NewsDto;
import com.echo.fm.content.news.type.INewsTypeService;
import com.echo.fm.content.news.type.model.NewsType;
import com.echo.util.ErrorException;
import com.echo.util.JSONResult;
import com.echo.util.JsonPagingData;
import com.echo.util.PagingInfo;
import com.echo.util.ResultUtils;
import com.echo.util.SystemWebConstant;
import com.echo.util.TimeGetter;
import com.echo.util.impl.DateUtils;
import com.echo.util.impl.HeaderParser;
import com.echo.util.impl.ValidateUtils;

@Controller
public class INewsController {

	@Autowired
	@Qualifier("newsService")
	INewsService newsService;

	@Autowired
	@Qualifier("newsTypeService")
	INewsTypeService newsTypeService;

	@RequestMapping(value = "web/news/guide")
	public String newsTemplate(HttpServletRequest request, HttpServletResponse response) {
		return "/pages/content/news/news-add";

	}

	@RequestMapping(value = "/web/news/createPage")
	public String addNewsPage(HttpServletRequest request, HttpServletResponse response) throws ErrorException {
		Admin detail = HeaderParser.getUser(request);
		if (detail == null) {
			throw new ErrorException(ResultUtils.WEB_PARAM_ERROR_CODE);
		}
		List<NewsType> newsTypeList = newsTypeService.searchNewsTypeList();
		request.setAttribute("selectList", newsTypeList);
		return "/pages/content/news/news-add";
	}

	@RequestMapping(value = "/web/news/listPage")
	public String listPage(HttpServletRequest request, HttpServletResponse response) throws ErrorException {
		Admin detail = HeaderParser.getUser(request);
		if (detail == null) {
			throw new ErrorException(ResultUtils.WEB_DB_SERVER_ERROR_CODE);
		}

		NewsType newsType = null;
		String id = request.getParameter("id");
		if (ValidateUtils.isNotEmpty(id)) {
			newsType = newsTypeService.searchNewsTypeId(Integer.valueOf(id));
		}
		request.setAttribute("newsType", newsType);
		return "/pages/content/news/news-list";

	}

	@RequestMapping(value = "/web/news/editPage")

	public String editPage(HttpServletRequest request, HttpServletResponse response) throws ErrorException {
		Admin detail = HeaderParser.getUser(request);
		if (detail == null) {
			throw new ErrorException(ResultUtils.WEB_PARAM_ERROR_CODE);
		}
		News news = null;
		String id = request.getParameter("id");
		if (ValidateUtils.isNotEmpty(id)) {
			news = newsService.searchNewsById(id);
		}
		List<NewsType> newsTypeList = newsTypeService.searchNewsTypeList();
		request.setAttribute("selectList", newsTypeList);
		request.setAttribute("news", news);
		return "/pages/content/news/news-edit";
	}

	@RequestMapping(value = "/web/news/addSave", method = { RequestMethod.GET, RequestMethod.POST })
	@ResponseBody
	Object addNews(HttpServletRequest request, HttpServletResponse response) throws ErrorException {

		try {
			Admin detail = HeaderParser.getUser(request);
			if (detail == null) {
				throw new ErrorException(ResultUtils.WEB_DB_SERVER_ERROR_CODE);
			}

			News news = new News();
			String title = request.getParameter("title");
			if (ValidateUtils.isNotEmpty(title)) {
				news.setTitle(title);
			}
			String oper = request.getParameter("oper");
			if (ValidateUtils.isNotEmpty(oper)) {
				news.setOper(oper);
			}
			String image = request.getParameter("image");
			if (ValidateUtils.isNotEmpty(image)) {
				news.setImage(image);
			}
			String content = request.getParameter("content");
			if (ValidateUtils.isNotEmpty(content)) {
				news.setContent(content);
			}
			String newsType = request.getParameter("newsType");
			if (ValidateUtils.isNotEmpty(newsType)) {
				news.setNewsType(Integer.valueOf(newsType));
			}
			String url = request.getParameter("url");
			if (ValidateUtils.isNotEmpty(url)) {
				news.setUrl(url);
			}

			String openUrl = request.getParameter("openUrl");
			if (ValidateUtils.isNotEmpty(openUrl)) {
				news.setOpenUrl(openUrl);
			}

			String status = request.getParameter("status");
			if (ValidateUtils.isNotEmpty(status)) {
				if ("on".equals(status)) {
					news.setStatus(1);
				} else {
					news.setStatus(0);
				}
			}
			String sort = request.getParameter("sort");
			if (ValidateUtils.isNotEmpty(sort)) {
				news.setSort(Double.parseDouble(sort));
			}
			news.setTimeL(TimeGetter.getTime());
			String startTime = request.getParameter("startTime");
			String endTime = request.getParameter("endTime");
			if (ValidateUtils.isValidDate(startTime) && ValidateUtils.isValidDate(endTime)) {
				SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
				Calendar calendar = Calendar.getInstance(Locale.CHINA);
				try {
					calendar.setTime(dateFormat.parse(startTime));
				} catch (ParseException e) {
					e.printStackTrace();
				}
				news.setStartTimeL(calendar.getTimeInMillis());

				try {
					calendar.setTime(dateFormat.parse(endTime));
				} catch (ParseException e) {
					e.printStackTrace();
				}
				news.setEndTimeL(calendar.getTimeInMillis());
			}

			String isTop_str = request.getParameter("istop");
			if (ValidateUtils.isNotEmpty(isTop_str)) {
				news.setIsLoop(Integer.valueOf(isTop_str));
			}
			news.setId(UUID.randomUUID().toString().replaceAll("-", ""));
			newsService.addNews(news);

			return ResultUtils.instJSONResult(ResultUtils.WEB_SUCCESS_CODE);
		} catch (NumberFormatException e) {
			e.printStackTrace();
			return ResultUtils.instJSONResult(ResultUtils.WEB_DB_SERVER_ERROR_CODE);
		}

	}

	/**
	 * 新闻详情
	 * 
	 * @param request
	 * @param response
	 * @return
	 */

	@RequestMapping(value = "/web/news/detail", method = { RequestMethod.GET, RequestMethod.POST })
	@ResponseBody
	Object newsDetail(HttpServletRequest request, HttpServletResponse response) {
		try {
			News news = new News();
			String id = request.getParameter("id");
			if (ValidateUtils.isNotEmpty(id)) {
				newsService.searchNewsById(id);
			} else {
				throw new ErrorException(ResultUtils.WEB_PARAM_ERROR_CODE);
			}
			JSONResult jsonResult = ResultUtils.instJSONResult(ResultUtils.WEB_SUCCESS_CODE);
			jsonResult.setData(news);
			return jsonResult;
		} catch (Exception e) {
			e.printStackTrace();
			return ResultUtils.instJSONResult(ResultUtils.WEB_DB_SERVER_ERROR_CODE);
		}
	}

	/**
	 * 修改新闻
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws ErrorException
	 */
	@RequestMapping(value = "/web/news/updateSave", method = { RequestMethod.GET, RequestMethod.POST })
	@ResponseBody
	Object updateNews(HttpServletRequest request, HttpServletResponse response) throws ErrorException {

		try {
			Admin detail = HeaderParser.getUser(request);
			if (detail == null) {
				throw new ErrorException(ResultUtils.WEB_DB_SERVER_ERROR_CODE);
			}

			String id = request.getParameter("id");
			News newsExist = newsService.searchNewsById(id);
			if (newsExist != null) {
				String title = request.getParameter("title");
				if (ValidateUtils.isNotEmpty(title)) {
					newsExist.setTitle(title);
				}
				String oper = request.getParameter("oper");
				if (ValidateUtils.isNotEmpty(oper)) {
					newsExist.setOper(oper);
				}
				String content = request.getParameter("content");
				if (ValidateUtils.isNotEmpty(content)) {
					newsExist.setContent(content);
				}

				String image = request.getParameter("image");
				if (ValidateUtils.isNotEmpty(image)) {
					newsExist.setImage(image);
				}
				String newsType = request.getParameter("newsType");
				if (ValidateUtils.isNotEmpty(newsType)) {
					newsExist.setNewsType(Integer.valueOf(newsType));
				}
				String url = request.getParameter("url");
				if (ValidateUtils.isNotEmpty(url)) {
					newsExist.setUrl(url);
				}
				String sort = request.getParameter("sort");
				if (ValidateUtils.isNotEmpty(sort)) {
					newsExist.setSort(Double.parseDouble(sort));
				}
				String openUrl = request.getParameter("openUrl");
				if (ValidateUtils.isNotEmpty(openUrl)) {
					newsExist.setOpenUrl(openUrl);
				}
				String status = request.getParameter("status");
				if (ValidateUtils.isNotEmpty(status)) {
					if ("on".equals(status)) {
						newsExist.setStatus(1);
					} else {
						newsExist.setStatus(0);
					}
				}

				String isTop_str = request.getParameter("istop");
				if (ValidateUtils.isNotEmpty(isTop_str)) {
					newsExist.setIsLoop(Integer.valueOf(isTop_str));
				}
				newsExist.setTimeL(TimeGetter.getTime());
				String startTime = request.getParameter("startTime");
				String endTime = request.getParameter("endTime");
				if (ValidateUtils.isValidDate(startTime) && ValidateUtils.isValidDate(endTime)) {
					SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
					Calendar calendar = Calendar.getInstance(Locale.CHINA);
					try {
						calendar.setTime(dateFormat.parse(startTime));
					} catch (ParseException e) {
						e.printStackTrace();
					}
					newsExist.setStartTimeL(calendar.getTimeInMillis());
					try {
						calendar.setTime(dateFormat.parse(endTime));
					} catch (ParseException e) {
						e.printStackTrace();
					}
					newsExist.setEndTimeL(calendar.getTimeInMillis());
				}

			}
			newsService.updateNewsById(newsExist);
			return ResultUtils.instJSONResult(ResultUtils.WEB_SUCCESS_CODE);
		} catch (NumberFormatException e) {
			e.printStackTrace();
			return ResultUtils.instJSONResult(ResultUtils.WEB_DB_SERVER_ERROR_CODE);
		}

	}

	/**
	 * 修改新闻的状态
	 * 
	 * @param response
	 * @param request
	 * @return
	 * @throws ErrorException
	 */

	@RequestMapping(value = "/web/news/updateStatus", method = { RequestMethod.GET, RequestMethod.POST })
	@ResponseBody
	Object updateStatus(HttpServletRequest request, HttpServletResponse response) throws ErrorException {

		try {
			Admin detail = HeaderParser.getUser(request);
			if (detail == null) {
				throw new ErrorException(ResultUtils.WEB_DB_SERVER_ERROR_CODE);
			}
			String id = request.getParameter("id");
			News editNews = newsService.searchNewsById(id);
			String status = request.getParameter("status");
			if (ValidateUtils.isNotEmpty(status)) {
				if (Integer.valueOf(status) == 0) {
					editNews.setStatus(1);
				} else if (Integer.valueOf(status) == 1) {
					editNews.setStatus(-1);
				}
			}
			newsService.updateNewsById(editNews);
			return ResultUtils.instJSONResult(ResultUtils.WEB_SUCCESS_CODE);
		} catch (ErrorException e) {
			e.printStackTrace();
			return ResultUtils.instJSONResult(ResultUtils.WEB_DB_SERVER_ERROR_CODE);
		}

	}

	@RequestMapping(value = "/web/news/deleteSave", method = { RequestMethod.GET, RequestMethod.POST })
	@ResponseBody
	Object deleteNews(HttpServletRequest request, HttpServletResponse response) throws ErrorException {
		try {
			Admin detail = HeaderParser.getUser(request);
			if (detail == null) {
				throw new ErrorException(ResultUtils.WEB_DB_SERVER_ERROR_CODE);
			}
			String id = request.getParameter("id");
			News news = newsService.searchNewsById(id);
			if (news != null) {
				newsService.deleteNews(news);
			}
			return ResultUtils.instJSONResult(ResultUtils.WEB_SUCCESS_CODE);
		} catch (Exception e) {
			e.printStackTrace();
			return ResultUtils.instJSONResult(ResultUtils.WEB_DB_SERVER_ERROR_CODE);
		}

	}

	@RequestMapping(value = "/web/news/updateShow")
	public Object updateShow(HttpServletRequest request, HttpServletResponse response) throws ErrorException {

		try {
			Admin detail = HeaderParser.getUser(request);
			if (detail == null) {
				throw new ErrorException(ResultUtils.WEB_DB_SERVER_ERROR_CODE);
			}
			String id = request.getParameter("id");
			News newsExist = newsService.searchNewsById(id);
			newsExist.setIsLoop(0);
			String isLoop = request.getParameter("isLoop");
			if (ValidateUtils.isNotEmpty(isLoop)) {
				if (Integer.valueOf(isLoop) == 1) {
					newsExist.setIsLoop(1);
				}
			}
			String sort = request.getParameter("order");
			if (ValidateUtils.isNotEmpty(sort)) {
				newsExist.setSort(Double.parseDouble(sort));
			}
			String status_str = request.getParameter("status");
			if (ValidateUtils.isNotEmpty(status_str)) {
				newsExist.setStatus(Integer.valueOf(status_str));
			}
			newsService.updateNewsById(newsExist);
			return ResultUtils.instJSONResult(ResultUtils.WEB_SUCCESS_CODE);

		} catch (ErrorException e) {
			e.printStackTrace();
			return new ErrorException(ResultUtils.WEB_DB_SERVER_ERROR_CODE);
		}

	}

	// http://localhost:8080/demo/web/news/list?status=1
	@RequestMapping(value = "/web/news/list")
	@ResponseBody
	Object listNews(HttpServletResponse response, HttpServletRequest request) {
		try {
			Admin detail = HeaderParser.getUser(request);
			if (detail == null) {
				return ResultUtils.instJSONResult(ResultUtils.WEB_DB_SERVER_ERROR_CODE);
			}
			/**
			 * 按类别查询
			 */
			Integer newsType = null;
			String newsTypeStr = request.getParameter("newsType");
			if (ValidateUtils.isNotEmpty(newsTypeStr)) {
				newsType = Integer.valueOf(newsTypeStr);
			}
			/**
			 * 按状态查询
			 */
			Integer status = null;
			String statusStr = request.getParameter("status");
			if (ValidateUtils.isNotEmpty(statusStr)) {
				status = Integer.valueOf(statusStr);
			}
			/**
			 * 按开始时间和结束时间查询
			 */
			Long searchStartTime = null;
			Long searchfinalTime = null;
			// request.setCharacterEncoding("UTF-8");
			String startTimeStr = request.getParameter("startTime");
			String endTimeStr = request.getParameter("endTime");
			if (ValidateUtils.isValidDate(startTimeStr) && ValidateUtils.isValidDate(endTimeStr)) {
				searchStartTime = DateUtils.str2DateL(startTimeStr);
				searchfinalTime = DateUtils.str2EDateL(endTimeStr);
			}
			/**
			 * 按title标查询
			 */
			String title = null;
			String paramTitle = request.getParameter("title");
			if (ValidateUtils.isNotEmpty(paramTitle)) {
				title = new String(paramTitle.getBytes("ISO-8859-1"), "UTF-8");
			}
			String page = request.getParameter("page");
			PagingInfo pagingInfo = new PagingInfo();
			int firstResult = 0;
			if (ValidateUtils.isNotEmpty(page)) {
				firstResult = (Integer.parseInt(page) - 1) * SystemWebConstant.DEFAULT_PAGE_SIZE;
				pagingInfo.setCurrentPage(Integer.valueOf(page));
			}
			List<NewsDto> dataList = newsService.listSearchNews(title, searchStartTime, searchfinalTime, status,
					newsType, SystemWebConstant.DEFAULT_PAGE_SIZE, firstResult);
			JSONResult jsonResult = ResultUtils.instJSONResult(ResultUtils.WEB_SUCCESS_CODE);

			JsonPagingData jsonPagingData = new JsonPagingData();
			jsonPagingData.setPaging(pagingInfo);
			jsonPagingData.setList(dataList);
			jsonResult.setData(jsonPagingData);
			return jsonResult;

		} catch (Exception e) {
			e.printStackTrace();
			return ResultUtils.instJSONResult(ResultUtils.WEB_DB_SERVER_ERROR_CODE);
		}
	}

}
